﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using PanasonicWarranty.Business;
using System.Web.UI.HtmlControls;
using Utils;
using Settings;
using System.Data;
using System.Data.SqlClient;


namespace PanasonicWarranty.UI
{
    public partial class ApproveWarrantyManagement : BasePage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        void paging_PagingChange(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            pagingbottom.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            BindGridData();
            pagingtop.Visible = pagingbottom.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PageSize = Convert.ToInt32(tSortable_length.SelectedValue);
                pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
                pagingtop.PageSize = pagingbottom.PageSize = PageSize;
                pagingtop.PageDisplay = pagingbottom.PageDisplay = 6;
                BindDropDownData();
                BindGridData();
            }
        }

        private void BindGridData()
        {
            try
            {
                int currentPage = pagingtop.CurrentPage;
                int pageSize = pagingtop.PageSize;
                int totalRow = 0;
                string category = ddlSearchCategory.SelectedValue;
                string model = ddlSearchModel.SelectedValue;
                string productcode = txtSearchProductCode.Text.Trim();
                int? agencyid = null;
                if (!string.IsNullOrEmpty(ddlSearchAgency.SelectedValue))
                    agencyid = int.Parse(ddlSearchAgency.SelectedValue);
                DateTime? fromRegisterDate = string.IsNullOrWhiteSpace(txtSearchFromDate.Text) ?
                                            (DateTime?)null :
                                            Convert.ToDateTime(txtSearchFromDate.Text.Trim(), DateTimeFormat);
                DateTime? toRegisterDate = string.IsNullOrWhiteSpace(txtSearchToDate.Text) ?
                                            (DateTime?)null :
                                            Convert.ToDateTime(txtSearchToDate.Text.Trim(), DateTimeFormat);
                string phone = txtSearchPhone.Text;
                bool? happycall = ddlSearchHappyCall.SelectedValue == "" ? (bool?)null : bool.Parse(ddlSearchHappyCall.SelectedValue);
                grvData.DataSource = pa_WarrantyWaiting.Paging(currentPage, pageSize, ref totalRow, agencyid, category, model, productcode, phone, fromRegisterDate, toRegisterDate, happycall);
                pagingtop.TotalRecord = pagingbottom.TotalRecord = totalRow;
                pagingtop.Visible = pagingbottom.Visible = pagingtop.TotalPage > 1;
                grvData.DataBind();
                ltrInfo.Text = "Tổng cộng: " + totalRow;
            }
            catch { }
        }

        private void BindDropDownData()
        {
            try
            {
                BindDropDownListData(ddlSearchModel, pa_Model.GetAll(false), "ModelCode", "ModelCode", new ListItem(""));
                BindDropDownListData(ddlShortCode, SmsShortCode.GetAll(), "ShortCode", "ShortCode");
                BindDropDownListData(ddlSearchCategory, pa_Category.GetAll(false), "CateCode", "CateCode", new ListItem());
                List<pa_Agency> list;
                bool isAdmin = IsRootAdmin();
                if (isAdmin)
                    list = pa_Agency.GetAll();
                else
                    list = pa_Agency.GetAll(CurUser.AgencyID.Value);
                pa_Agency.TransformLevel(ref list);
                foreach (var item in list)
                {
                    ddlSearchAgency.Items.Add(new ListItem(item.AgencyName.ShowNameLevel(item.Level), item.AgencyID.ToString()));
                }
                if (isAdmin)
                    ddlSearchAgency.Items.Insert(0, new ListItem(""));
            }
            catch { }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
            BindGridData();
        }

        protected void tSortable_length_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                PageSize = Convert.ToInt32(tSortable_length.SelectedValue);
                pagingtop.PageSize = pagingbottom.PageSize = PageSize;
                BindGridData();
            }
            catch { }
        }

        protected void ddlSearchCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindDropDownListData(ddlSearchModel, pa_Model.GetByCategory(ddlSearchCategory.SelectedValue, false), "ModelCode", "ModelCode", new ListItem(""));
            ddlSearchCategory.Focus();
        }

        protected void btnSendSMS_Click(object sender, EventArgs e)
        {
            try
            {
                Authorize(Role.Write);
                pa_WarrantyWaiting objWaiting = pa_WarrantyWaiting.GetByID(int.Parse(hdfID.Value));
                if (objWaiting != null)
                {
                    //Xử lý nghiệp vụ
                    using (SqlConnection conn = new SqlConnection(AppSetting.ConnectionString))
                    {
                        conn.Open();
                        using (SqlTransaction trans = conn.BeginTransaction())
                        {
                            if (pa_Warranty.Insert(trans,objWaiting, pa_WarrantyStatus.GetByCode(eWarrantyStatus.XACNHANBAOHANH).WarrantyStatusID, UserID.Value, txtSms.Text))
                            {
                                //Thêm dữ liệu vào bảng SmsMtWaiting
                                SmsMtWaiting.Insert(ddlShortCode.SelectedValue, txtSms.Text, objWaiting.AgencyID, objWaiting.CustomerPhone);
                            }
                            trans.Commit();
                        }
                    }
                    //Ghi log dữ liệu
                    InsertChangeLog("Gửi tin nhắn xác nhận bảo hành");
                    //Reload dữ liệu
                    BindGridData();
                    RegisterStartUpScript("$('#dialog1').dialog('close');");
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        protected void btnHappyCall_Click(object sender, EventArgs e)
        {
            try
            {
                Authorize(Role.Write);
                pa_WarrantyWaiting objWaiting = pa_WarrantyWaiting.GetByID(int.Parse(hdfID.Value));
                if (objWaiting != null)
                {
                    using (SqlConnection conn = new SqlConnection(AppSetting.ConnectionString))
                    {
                        conn.Open();
                        using (SqlTransaction trans = conn.BeginTransaction())
                        {
                            if (pa_Warranty.Insert(trans, objWaiting, pa_WarrantyStatus.GetByCode(eWarrantyStatus.HAPPYCALL).WarrantyStatusID, UserID.Value, txtSms.Text))
                            {
                                if (chkSendSMS.Checked)
                                {
                                    //Thêm dữ liệu vào bảng SmsMtWaiting
                                    SmsMtWaiting.Insert(ddlShortCode.SelectedValue, txtSms.Text, objWaiting.AgencyID, objWaiting.CustomerPhone);
                                    //Ghi log dữ liệu
                                    InsertChangeLog("Xác nhận thực hiện happy call và gửi tin xác nhận bảo hành");
                                }
                                else
                                {
                                    //Ghi log dữ liệu
                                    InsertChangeLog("Xác nhận thực hiện happy call");
                                }
                            }
                            else
                            {
                                //Ghi log dữ liệu
                                InsertChangeLog("Xác nhận thực hiện happy call");
                            }
                            trans.Commit();
                        }
                    }
                    //Reload dữ liệu
                    BindGridData();
                    RegisterStartUpScript("$('#dialog1').dialog('close');");
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        protected void btnRejectWarranty_Click(object sender, EventArgs e)
        {
            try
            {
                Authorize(Role.Write);
                if (!string.IsNullOrWhiteSpace(txtRejectWarranty.Text))
                {
                    using (var context = new DBWarrantyDataContext(AppSetting.ConnectionString))
                    {
                        pa_WarrantyWaiting objWaiting = context.pa_WarrantyWaitings.FirstOrDefault(p => p.WarrantyWattingID == int.Parse(hdfID.Value));
                        if (objWaiting != null)
                        {
                            objWaiting.IsValid = false;
                            objWaiting.Approved = false;
                            objWaiting.Description = txtRejectWarranty.Text;
                            context.SubmitChanges();
                            pa_WarrantyDetailReject.Insert(context, objWaiting, UserID, txtRejectWarranty.Text.Trim());
                            if (objWaiting.RegisteredFrom == eRegisteredFrom.SMS)
                            {
                                string mesage = pa_MessagePattern.SingletonInstance[eMessagePattern.MAUTUCHOIBH]
                                            .Replace("(Model)", objWaiting.ModelCode)
                                            .Replace("(SoMay)", objWaiting.ProductCode)
                                            .Replace("(LyDo)", txtRejectWarranty.Text.Trim().ToVietnameseWithoutAccent());
                                SmsMtWaiting.Insert(AppSetting.DefaultSenderName, mesage, objWaiting.AgencyID, objWaiting.RegisteredPhone);
                            }
                            InsertChangeLog(string.Format("Từ chối bảo hành: Model: {0}, số máy: {1}, Lý do: {2}", objWaiting.ModelCode, objWaiting.ProductCode, txtRejectWarranty.Text.Trim()));
                            BindGridData();
                            RegisterStartUpScript("$('#dialog4').dialog('close')");
                        }
                    }
                }
                else
                {
                    lbValidateRejectWarranty.Text = "(*)";
                    RegisterStartUpScript("OpenDialog('dialog4',500);");
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                Authorize(Role.Export);
                string model = ddlSearchModel.SelectedValue;
                string productcode = txtSearchProductCode.Text.Trim();
                int? agencyid = null;
                if (!string.IsNullOrEmpty(ddlSearchAgency.SelectedValue))
                    agencyid = int.Parse(ddlSearchAgency.SelectedValue);
                DateTime? fromDate = string.IsNullOrWhiteSpace(txtSearchFromDate.Text) ?
                                            (DateTime?)null :
                                            Convert.ToDateTime(txtSearchFromDate.Text.Trim(), DateTimeFormat);
                DateTime? toDate = string.IsNullOrWhiteSpace(txtSearchToDate.Text) ?
                                            (DateTime?)null :
                                            Convert.ToDateTime(txtSearchToDate.Text.Trim(), DateTimeFormat);
                string phone = txtSearchPhone.Text;
                bool? happycall = ddlSearchHappyCall.SelectedValue == "" ? (bool?)null : bool.Parse(ddlSearchHappyCall.SelectedValue);
                using(DataTable dt = ObjectClass.CreateDynamicTable(pa_WarrantyWaiting.GetAll(agencyid, model, productcode, phone, fromDate, toDate, happycall)))
                {
                    if (dt == null || dt.Rows.Count == 0)
                        ShowMessageBox("Không có dữ liệu export");
                    else if (dt.Rows.Count > 0)
                    {
                        using (DataTable dtSource = dt.DefaultView.ToTable(false,
                            "ModelCode", "ProductCode", "CustomerPhone", "WarrantyPackageCode", "RegisterDate", "CreatedDate",
                            "WarrantyType", "Detail", "RegisteredFrom"))
                        {
                            foreach (DataColumn col in dtSource.Columns)
                                col.Caption = pa_WarrantyWaiting.GetCaption(col.ColumnName);
                            ExportToExcel(dtSource, "ExportThongTinDuLieuDangKyBaoHanh.xlsx");
                        }
                    }
                }
                InsertChangeLog("Export dữ liệu thông tin đăng ký bảo hành");
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }        
        }

        [WebMethod]
        public static string ApproveWarranty(int id)
        {
            return pa_MessagePattern.GetMessage(id);
        }
    }
}